﻿using AutoUpdate.Log;
using Microsoft.Win32;
using ScannerApp.Common;
using ScannerApp.Common.Print;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using static ScannerApp.Model.OperationType;

namespace ScannerApp.SingleBusiness
{
    /// <summary>
    /// EditBQ.xaml 的交互逻辑
    /// </summary>
    public partial class EditBQ : Window
    {
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");
          IniFiles iniprint = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\PrintIni.INI");
        string LogoPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Logo\";
        ObservableCollection<ListBoxItem> lbi = new ObservableCollection<ListBoxItem>();
        public EditBQ()
        {
            InitializeComponent();
        }
        private void EditBQ_Loaded(object sender, RoutedEventArgs e)
        {
            string langName = "zh-CN",bq= "DemoBoarID";
            try
            {
                langName = ini.IniReadValue("公司信息", "SelectLanguages"); //Common.ConfigHelper.GetIni("COM", "");
                 bq= ini.IniReadValue("公司信息", "SelectPrintTag");//选择标签
                string ProImgPath = LogoPath + @"\PrintLogo.png";//要保存的图片的地址，包含文件名
                                                                 //Image_New.Source = new BitmapImage(new Uri(ProImgPath));
                var r = IsZebarPrint();
               var uptip = "";
                if (r.Item1)
                    lbupload.SetResourceReference(TextBlock.TextProperty, "sBQuploadtip");
               // lbupload.Content = "请上传150*30黑白png照片";
                else lbupload.SetResourceReference(TextBlock.TextProperty, "sBQuploadtip2"); 
                //lbupload.Content = "请上传150*30黑白pcx照片";
            }
            catch { }

            Dictionary<string, string> d = new Dictionary<string, string>();
            if (langName == "zh-CN")
            {
                foreach (FontFamily _f in Fonts.SystemFontFamilies)
                {
                    LanguageSpecificStringDictionary _font = _f.FamilyNames;
                    if (_font.ContainsKey(System.Windows.Markup.XmlLanguage.GetLanguage("zh-cn")))
                    {
                        string _fontName = null;
                        if (_font.TryGetValue(System.Windows.Markup.XmlLanguage.GetLanguage("zh-cn"), out _fontName))
                        {
                            dzzt.Items.Add(_fontName);
                            btzt.Items.Add(_fontName);
                            pzzt.Items.Add(_fontName);
                            phzt.Items.Add(_fontName);
                            dwzt.Items.Add(_fontName);
                            rqzt.Items.Add(_fontName);
                            syrqzt.Items.Add(_fontName);
                            zdy1zt.Items.Add(_fontName);
                            zdy2zt.Items.Add(_fontName);
                            snzt.Items.Add(_fontName);
                            ebbtzt.Items.Add(_fontName);
                            //jczt.Items.Add(_fontName);
                            densityzt.Items.Add(_fontName);
                            vitalityzt.Items.Add(_fontName);
                            vaildzt.Items.Add(_fontName);
                            totalzt.Items.Add(_fontName);
                            fullzt.Items.Add(_fontName);
                        }
                    }
                }
            }
            else if (langName == "en-US")
            {
                foreach (FontFamily font in Fonts.SystemFontFamilies)
                {
                    dzzt.Items.Add(font.Source);
                    btzt.Items.Add(font.Source);
                    pzzt.Items.Add(font.Source);
                    phzt.Items.Add(font.Source);
                    dwzt.Items.Add(font.Source);
                    rqzt.Items.Add(font.Source);
                    syrqzt.Items.Add(font.Source);
                    zdy1zt.Items.Add(font.Source);
                    zdy2zt.Items.Add(font.Source);
                    snzt.Items.Add(font.Source);
                    ebbtzt.Items.Add(font.Source);
                    //jczt.Items.Add(font.Source);
                    densityzt.Items.Add(font.Source);
                    vitalityzt.Items.Add(font.Source);
                    vaildzt.Items.Add(font.Source);
                    totalzt.Items.Add(font.Source);
                }
            }
            else {
                foreach (FontFamily font in Fonts.SystemFontFamilies)
                {
                    dzzt.Items.Add(font.Source);
                    btzt.Items.Add(font.Source);
                    pzzt.Items.Add(font.Source);
                    phzt.Items.Add(font.Source);
                    dwzt.Items.Add(font.Source);
                    rqzt.Items.Add(font.Source);
                    syrqzt.Items.Add(font.Source);
                    zdy1zt.Items.Add(font.Source);
                    zdy2zt.Items.Add(font.Source);
                    //jczt.Items.Add(font.Source);
                    densityzt.Items.Add(font.Source);
                    vitalityzt.Items.Add(font.Source);
                    vaildzt.Items.Add(font.Source);
                    totalzt.Items.Add(font.Source);

                }
            }
            //case "sp":
            //          break;
            //case "gq4":
            //            break;
            //case "gq5":
            //          break;
            //case "gq6":
            //          break;
            //case "pty":
            //             break;
            //case "gq8":

            InitFNT();
            initOrigin();
            string flag = "";
            if (!IsExistIni()) flag = "不存在标签配置文件！PrintIni.INI";
            List<string> l = iniprint.IniReadSection();
            lbi.Clear();
            //l.ForEach(num => lbi.Add(new ListBoxItem(num))  );
            int i = 0,selectbq=0;
            foreach (var item in l)
            {
                lbi.Add(new ListBoxItem(i, item));
                if (bq == item)
                    selectbq = i;
                i++;
               
            }
            this.list.ItemsSource = lbi;
            list.SelectedIndex = selectbq;
          
        }
          bool IsExistIni()
        {

            if (iniprint.ExistINIFile())
            {
                return true;
            }
            else return false;
        }

        void InitFNT()
        {
            fontName.Items.Clear();
            for (int i = 1; i < 30; i++) {
                try {
                    //   zdy1zt.Items.Add(_fontName);
                    string s = ini.IniReadValue("打印字体", "FNT" + i);
                       if(s!="")
                       fontName.Items.Add(s ); ;
                } catch(Exception ex) {
                    break;
                }
            }
            // langName = ini.IniReadValue("打印字体", "FNT1");

        }

        void initOrigin() {
            orgindic.Items.Clear();
          
            orgindic.Items.Add(new ListBoxItem(1,"Normal"));
      
            orgindic.Items.Add(new ListBoxItem(2, "90 degress"));
           
            orgindic.Items.Add(new ListBoxItem(3, "180 degress"));
          
            orgindic.Items.Add(new ListBoxItem(4, "270 degress"));

        }
     
        private void btn_save(object sender, RoutedEventArgs e)
        {
            try
            {
                string s = "";
                try
                {
                    s = ((ListBoxItem)list.SelectedItem).Name;
                    if (s == "")
                    {
                        tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                        MessageBox.Show(tipslan.Text);

                        return;
                    }

                }
                catch (Exception ex)
                {
                    tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                    MessageBox.Show(tipslan.Text);

                    return;
                }
                try
                {
                    string f = fontName.SelectedItem.ToString();
                    if (f == "" || f == null)
                    {
                        tipslan.SetResourceReference(TextBlock.TextProperty, "sInfo3");
                        MessageBox.Show(tipslan.Text);

                        return;
                    }
                }
                catch { }
                if (s == "DemoBoarID" || s == "DemoBoarIDs")
                {
                    tipslan.SetResourceReference(TextBlock.TextProperty, "sInfo1");
                    MessageBox.Show(tipslan.Text);
                    return;
                }

                if (zdy1xs.IsChecked == true && zdy2xs.IsChecked == true)
                {
                    tipslan.SetResourceReference(TextBlock.TextProperty, "sInfo2");
                    MessageBox.Show(tipslan.Text);
                    return;
                }
                if (zdy1xs.IsChecked == false && zdy2xs.IsChecked == false)
                {
                    tipslan.SetResourceReference(TextBlock.TextProperty, "sInfo2");
                    MessageBox.Show(tipslan.Text);
                    return;
                }
                writeIniNewBQ(s);
                tipslan.SetResourceReference(TextBlock.TextProperty, "sInfsave");
                    MessageBox.Show(tipslan.Text);
                PrintEntity pe = PrintPre();
                var r = IsZebarPrint();
                if (r.Item2== PrintTypes.Zebra.ToString())
                     Common.Print.ZerbarPrint.ZerTSC_LocalImg(pe);  
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error:"+ ex.Message);
                return;
            }
        }
        private void btn_print(object sender, RoutedEventArgs e)
        {
            try
            {
                Write_Docment("测试第一步,接收指令" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"), "PrintTrace");
                try
                {
                    string s = ((ListBoxItem)list.SelectedItem).Name;
                    if (s == "")
                    {
                        tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                        MessageBox.Show(tipslan.Text);

                        return;
                    }
                }
                catch (Exception ex)
                {
                    tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                    MessageBox.Show(tipslan.Text);

                    return;
                }
               
               string printIP = ini.IniReadValue("TCPIP", "PrintIP");
                string   printstr = "York-ID0001/ID0002/ID0003/ID0004/ID0005/ID0006-SO-201910200001-2030/12/31-80ml-1";
                string f = "";
                PrintEntity pe = PrintPre();
                string close = "false";
                try { close = ini.IniReadValue("公司信息", "CloePrintType"); }
                catch { }
            // Common.Print.ZerbarPrint.ZerTSC_LocalImg(pe);

                if (close == "false")
                {
                    var r = IsZebarPrint();
                    if (r.Item2 == PrintTypes.ZebraZD420.ToString()) Common.Print.ZerbarPrint.ZerTSC2(pe);
                    else if (r.Item2 == PrintTypes.Zebra.ToString())
                    {
                        Common.Print.ZerbarPrint.ZerTSC_Print(pe); 
                    }
                    else if (r.Item2 == PrintTypes.Gainscha.ToString())
                    {
                        f = TSCLIB.TSC(pe);
                        if (f != "")
                            MessageBox.Show("Error:" + f);
                    }
                }
                else if (close == "true")
                {
                    Common.Print.ZerbarPrint.ZerTSC_Print(pe);
                }
              
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error:"+ ex.Message);
                return;
            }
        }
        private void btn_upload(object sender, RoutedEventArgs e)
        {
            Stream ms;
            byte[] picByte;
            string filter = "图像文件|*.jpg;*.png;*.jpeg;*.bmp;*.gif|所有文件|*.*";
            
             OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = filter 
            };
            openFileDialog.InitialDirectory = @"C:\Users\Administrator\Desktop";//文件选择的默认路径

            if ((bool)openFileDialog.ShowDialog())
            {
                
                    try
                    {

                        Image_New.Source = new BitmapImage(new Uri(openFileDialog.FileName));
                        if (!Directory.Exists(LogoPath)) Directory.CreateDirectory(LogoPath);
                        string ProImgPath = LogoPath + @"\PrintLogo.png";//要保存的图片的地址，包含文件名
                    var r = IsZebarPrint();
                        if (!r.Item1)
                        {
                            ProImgPath = LogoPath + @"\PrintLogo.bmp";
                        }
                        File.Delete(ProImgPath);
                        BitmapSource BS = (BitmapSource)Image_New.Source;
                        PngBitmapEncoder PBE = new PngBitmapEncoder();
                        PBE.Frames.Add(BitmapFrame.Create(BS));
                        using (Stream stream = File.Create(ProImgPath))
                        {
                            PBE.Save(stream);
                        }
                        lbupload.Content = "Success!";


                    }
                    catch (Exception ee)
                    {
                        lbupload.Content = "Error：\n" + ee.ToString();
                    }
                    finally
                    {

                    }
                
                 
             
                
            }
            else
            {
                return;
            }
        }

        
        private Tuple<bool, string> IsZebarPrint()
        {
            string flag = "";bool IsZer = false;
            string printsytle = ini.IniReadValue("打印类型", "PrintStyle");
            if (printsytle != "")
            {
                if (printsytle == PrintTypes.Zebra.ToString())
                {
                    flag = PrintTypes.Zebra.ToString();
                    IsZer = true;
                }
                else if (printsytle == PrintTypes.ZebraZD420.ToString())
                {
                    flag = PrintTypes.ZebraZD420.ToString();
                    IsZer = true;
                }
                else if (printsytle == PrintTypes.Gainscha.ToString())
                {
                    flag = PrintTypes.Gainscha.ToString();
                    IsZer = false;
                }
            }
            return new Tuple<bool, string>(IsZer,flag); 
        }

        private PrintEntity PrintPre()
        {
            string printIP = ini.IniReadValue("TCPIP", "PrintIP");
            string printstr = "York-ID0001/ID0002/ID0003/ID0004/ID0005/ID0006-SO-201910200001-2030/12/31-80ml-1";
            string s = ((ListBoxItem)list.SelectedItem).Name;
            PrintEntity pe = new PrintEntity();
            if (s == "")
            {
                tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                MessageBox.Show(tipslan.Text);
                return pe;
            }
            
            pe.Bq = s;
            pe.P_port = printIP;
            pe.Title = "公司名称";
            pe.BarCode = printstr;
            pe.Address = "地址名称";
            pe.Breed = "Breed:York";
            pe.LotNumber = "Batch: SO-201910200001";
            pe.UseBefore = "Use Date:" + DateTime.Now.ToString("yyyy-MM-dd");
            pe.ProdDate = "Pro.Date:" + DateTime.Now.ToString("yyyy-MM-dd");
            pe.FullID = "09ID0001111";
            pe.ID = "ID;ID0001";
            pe.Ml = "80ml";
            pe.IDs = "ID;ID0001;ID0002;ID0003;ID0004;ID0005;ID0006";
            pe.Dylsh = "SN:11";
            pe.Shortname = "NO.short";
            pe.Issingle = true;
            pe.SDensity = "sDensity";
            pe.SVitality = "sVitality";
            pe.SVaild = "sVaild";
            pe.STotal = "sTotal"; 
            pe.Zdy1 = ini.IniReadValue("公司信息", "bz1");
            pe.Zdy2 = ini.IniReadValue("公司信息", "bz2");
            pe.IsDebug = true;
            return pe;
        }

        //增加
        private void add_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.ModalDialog1.IsOpen = true;
        }
        //减少
        private void sub_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string s = ((ListBoxItem)list.SelectedItem).Name;
            if (s == "")
            {
                tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                MessageBox.Show(tipslan.Text);
                return;
            }
            if (s == "DemoBoarID" || s == "DemoBoarIDs")
            {
                tipslan.SetResourceReference(TextBlock.TextProperty, "sInfoudelete");
                MessageBox.Show(tipslan.Text); 
                return;
            }
            tipslan.SetResourceReference(TextBlock.TextProperty, "sdeleteBQ");
            MessageBoxResult result = System.Windows.MessageBox.Show(tipslan.Text, "tips", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                long i = iniprint.DeleteSection(((ListBoxItem)list.SelectedItem).Name);
                if (i > 0) {
                    UIAction(() =>
                    {
                        //list.Items.Remove(list.SelectedItem);
                       // list.ItemsSource = null;
                         List<string> l = iniprint.IniReadSection();
                        lbi.Clear();
                        //l.ForEach(num => lbi.Add( new ListBoxItem(num)) );
                        int ii = 0;
                        foreach (var item in l)
                        {
                            lbi.Add(new ListBoxItem(ii, item));
                            ii++;
                        }

                        this.list.ItemsSource = lbi;
                    });

                }

            }
            else
            {

            }
         
        }
     
        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }

        private void Dlg_OK_Click(object sender, RoutedEventArgs e)
        {
            string s= txtvalue.Text ;
            if (s.Length <= 0) return;
            writeIniNewBQ(s);
            {
                UIAction(() =>
                {

                   // list.ItemsSource = null;
                    List<string> l = iniprint.IniReadSection();
                    lbi.Clear();
                    int i = 0;
                      foreach(var item in l)
                        {
                        lbi.Add(new ListBoxItem(i, item));
                        i++; 
                      } 
                    this.list.ItemsSource = lbi; 
                });
            }
            ShowModalDialog_value(false, "");
        }
        private void Dlg_Close_Click(object sender, RoutedEventArgs e)
        {
            ShowModalDialog_value(false,  "" );
        }
        private void ShowModalDialog_value(bool bShow,  string tips)
        {
            this.ModalDialog1.IsOpen = bShow;
            if (bShow)
            {
                txtvalue.Text = tips;
            }
            // this.MainPanel.IsEnabled = !bShow;
        }

        void writeIniNewBQ(string section)
        {
            try
            {
                string orgi = "";
               string a=  ((ListBoxItem)orgindic.SelectedItem).ID.ToString();
                if (a == "1") orgi = "N";else if (a == "2") orgi = "R"; else if (a == "3") orgi = "I"; else if (a == "4") orgi = "B";

                iniprint.IniWriteValue(section, "Setting", cd.Text + "," + kd.Text+","+ orgi);
                 iniprint.IniWriteValue(section, "PrintFont", fontName.SelectedItem.ToString());
                if (cklogo.IsChecked == true)
                    iniprint.IniWriteValue(section, "Logo", logox.Text + "," + logoy.Text + "," + logoc.Text + "," + logok.Text);
                else iniprint.DeleteKey(section, "Logo");
                if (zdbarcode.IsChecked == true)
                    iniprint.IniWriteValue(section, "QRCODE", bcd.Text + "," + bkd.Text+","+bsize.Text);
                else iniprint.DeleteKey(section, "QRCODE");
                int xs = 0;
                if (ckzdy1.IsChecked == true)
                    iniprint.IniWriteValue(section, "Zdy1", defzdy1x.Text + "," + defzdy1y.Text + "," + defzdy1dx.Text + ",Microsoft YaHei UI," + xs);
                else iniprint.DeleteKey(section, "Zdy1");
                if (ckzdy2.IsChecked == true)
                    iniprint.IniWriteValue(section, "Zdy2", defzdy22x.Text + "," + defzdy22y.Text + "," + defzdy22dx.Text + ",Microsoft YaHei UI," + xs);
                else iniprint.DeleteKey(section, "Zdy2");
                if (ckxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "ADDRESS", dzX.Text + "," + dzY.Text + "," + dzdx.Text + "," + dzzt.SelectedValue + "," + dzjc.SelectedIndex);
                else iniprint.DeleteKey(section, "ADDRESS");
                if (btxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "Title", btX.Text + "," + btY.Text + "," + btdx.Text + "," + btzt.SelectedValue + "," + btjc.SelectedIndex);
                else iniprint.DeleteKey(section, "Title");
                if (pzxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "Breed", pzX.Text + "," + pzY.Text + "," + pzdx.Text + "," + pzzt.SelectedValue + "," +pzjc.SelectedIndex);
                else iniprint.DeleteKey(section, "Breed");
                if (phxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "LotNumber", phX.Text + "," + phY.Text + "," + phdx.Text + "," +phzt.SelectedValue + "," + phjc.SelectedIndex);
                else iniprint.DeleteKey(section, "LotNumber");
                if (dwxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "ml", dwX.Text + "," + dwY.Text + "," + dwdx.Text + "," + dwzt.SelectedValue + "," + dwjc.SelectedIndex);
                else iniprint.DeleteKey(section, "ml");
                if (syrqxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "UseBefore", syrqX.Text + "," + syrqY.Text + "," + syrqdx.Text + "," + syrqzt.SelectedValue + "," + syrqjc.SelectedIndex + "," + syrqgs.Text);
                else iniprint.DeleteKey(section, "UseBefore");
                if (rqxs.IsChecked == true)
                    iniprint.IniWriteValue(section, "ProdDate", rqX.Text + "," + rqY.Text + "," + rqdx.Text + "," + rqzt.SelectedValue + "," + rqjc.SelectedIndex + "," + rqgs.Text);
                else iniprint.DeleteKey(section, "ProdDate");
                if (sn.IsChecked == true)
                    iniprint.IniWriteValue(section, "sn", snX.Text + "," + snY.Text + "," + sndx.Text + "," + snzt.SelectedValue + "," + snjc.SelectedIndex);
                else iniprint.DeleteKey(section, "sn");
                if (ckfull.IsChecked == true)
                    iniprint.IniWriteValue(section, "fullName", fullX.Text + "," + fullY.Text + "," + fulldx.Text + "," + fullzt.SelectedValue + "," + fulljc.SelectedIndex);
                else iniprint.DeleteKey(section, "fullName");
                //if (jc.IsChecked == true)
                //    iniprint.IniWriteValue(section, "short", jcX.Text + "," + jcY.Text + "," + jcdx.Text + "," + jczt.SelectedValue + "," + xs);
                //else iniprint.DeleteKey(section, "short");
                if (zdy1xs.IsChecked == true)
                {
                    ini.IniWriteValue("公司信息", "SelectPrintMulti", "false");//选择标签
                    iniprint.IniWriteValue(section, "ID", zdy1X.Text + "," + zdy1Y.Text + "," + zdy1dx.Text + "," + zdy1zt.SelectedValue + "," + zdy1jc.SelectedIndex);
                    iniprint.IniWriteValue(section, "ID_", ebbtX.Text + "," + ebbtY.Text + "," + ebbtdx.Text + "," + ebbtzt.SelectedValue + "," + ebbtjc.SelectedIndex);

                }
                else
                {
                       iniprint.DeleteKey(section, "ID");
                    iniprint.DeleteKey(section, "ID_");
                }
                if (zdy2xs.IsChecked == true)
                {
                    ini.IniWriteValue("公司信息", "SelectPrintMulti", "true");//选择标签
                    iniprint.IniWriteValue(section, "IDs", zdy2X.Text + "," + zdy2Y.Text + "," + zdy2dx.Text + "," + zdy2zt.SelectedValue + "," + zdy2jc.SelectedIndex + "," + zdy2.Text);
                    iniprint.IniWriteValue(section, "IDs_", ebbtX.Text  + "," + ebbtY.Text + "," + ebbtdx.Text + "," + ebbtzt.SelectedValue + "," + ebbtjc.SelectedIndex + "," + zdy2.Text);

                }
                else {
                    iniprint.DeleteKey(section, "IDs");
                    iniprint.DeleteKey(section, "IDs_");
                }

                if (density.IsChecked == true)
                    iniprint.IniWriteValue(section, "density", densityX.Text + "," + densityY.Text + "," + densitydx.Text + "," + densityzt.SelectedValue + "," + densityjc.SelectedIndex);
                else iniprint.DeleteKey(section, "density");
                if (vitality.IsChecked == true)
                    iniprint.IniWriteValue(section, "vitality", vitalityX.Text + "," + vitalityY.Text + "," + vitalitydx.Text + "," + vitalityzt.SelectedValue + "," + vitalityjc.SelectedIndex);
                else iniprint.DeleteKey(section, "vitality");
                if (ckvaild.IsChecked == true)
                    iniprint.IniWriteValue(section, "vaild", vaildX.Text + "," + vaildY.Text + "," + vailddx.Text + "," + vaildzt.SelectedValue + "," + vaildjc.SelectedIndex);
                else iniprint.DeleteKey(section, "vaild");
                if (total.IsChecked == true)
                    iniprint.IniWriteValue(section, "total", totalX.Text + "," + totalY.Text + "," + totaldx.Text + "," + totalzt.SelectedValue + "," + totaljc.SelectedIndex);
                else iniprint.DeleteKey(section, "total");
                if (level.IsChecked == true)
                    iniprint.IniWriteValue(section, "level", levelX.Text + "," + levelY.Text + "," + leveldx.Text + "," + levelzt.SelectedValue + "," + leveljc.SelectedIndex); 
                else iniprint.DeleteKey(section, "level");
                //Setting = 70,40
                //QRCODE = 350,70
                //ADDRESS = 10,50,22,微软雅黑,0
                //Title = 10,10,32,微软雅黑,0
                //Breed = 10,120,34,微软雅黑,0
                //LotNumber = 10,170,34,微软雅黑,0
                //UseBefore = 10,220,34,微软雅黑,0,MM / dd / yyyy
                //ProdDate = 10,270,34,微软雅黑,0,MM / dd / yyyy
                //ID = 415,23,34,微软雅黑,2
                //ID_ = 370,25,30,微软雅黑,0
                //ml = 430,250,34,微软雅黑,2
            }
            catch (Exception ex)
            {
                MessageBox.Show("WriteError:"+ex.Message);
            }
    }

        void InitBQ(string section)
        {
            try
            {
                try
                {
                    string logo = iniprint.IniReadValue(section, "Logo");
                    if (logo.Length > 1)
                    {
                        string[] logs = logo.Split(',');
                        logox.Text = logs[0];
                        logoy.Text = logs[1];
                        logoc.Text = logs[2];
                        logok.Text = logs[3];
                        cklogo.IsChecked = true;
                    }
                    else cklogo.IsChecked = false;
                }
                catch { }
                try
                {
                    fontName.SelectedItem = iniprint.IniReadValue(section, "PrintFont");
                }
                catch { }

                string zdy1 = iniprint.IniReadValue(section, "Zdy1");
                if (zdy1.Length > 1)
                {
                    string[] zdy1s = zdy1.Split(',');
                    defzdy1x.Text = zdy1s[0];
                    defzdy1y.Text = zdy1s[1];
                    defzdy1dx.Text = zdy1s[2];
                    ckzdy1.IsChecked = true;
                }
                else ckzdy1.IsChecked = false;
                string zdy22 = iniprint.IniReadValue(section, "Zdy2");
                if (zdy22.Length > 1)
                {
                    string[] zdy22s = zdy22.Split(',');
                    defzdy22x.Text = zdy22s[0];
                    defzdy22y.Text = zdy22s[1];
                    defzdy22dx.Text = zdy22s[2];
                    ckzdy2.IsChecked = true; 
                }
                else ckzdy2.IsChecked = false;
                string rcd = iniprint.IniReadValue(section, "Setting");
                string[] rcds = rcd.Split(',');
                cd.Text = rcds[0];
                kd.Text = rcds[1];
                try
                {
                    string a = rcds[2];int orgi = 0;
                    if (a == "N") orgi = 1; else if (a == "R") orgi = 2; else if (a == "I") orgi = 3; else if (a == "B") orgi = 4;

                    orgindic.SelectedValue = orgi;
                }
                catch { }
                string rbar = iniprint.IniReadValue(section, "QRCODE");
                if (rbar.Length > 1)
                {
                    string[] rbars = rbar.Split(',');
                    bcd.Text = rbars[0];
                    bkd.Text = rbars[1];
                    bsize.Text = rbars[2];
                    zdbarcode.IsChecked = true;
                }
                else zdbarcode.IsChecked = false;
                string radd = iniprint.IniReadValue(section, "ADDRESS");
                if (radd.Length > 1)
                {
                    string[] radds = radd.Split(',');
                    dzX.Text = radds[0];
                    dzY.Text = radds[1];
                    dzdx.Text = radds[2];
                    dzzt.SelectedValue = radds[3];
                    dzjc.SelectedIndex= stringToInt( radds[4]);
                    ckxs.IsChecked = true;
                }
                else ckxs.IsChecked = false;


                string rbt = iniprint.IniReadValue(section, "Title");
                if (rbt.Length > 1)
                {
                    string[] rbts = rbt.Split(',');
                    btX.Text = rbts[0];
                    btY.Text = rbts[1];
                    btdx.Text = rbts[2];
                    btzt.SelectedValue = rbts[3];
                    btjc.SelectedIndex = stringToInt(rbts[4]);
                    btxs.IsChecked = true;
                }
                else btxs.IsChecked = false;
                string rbr = iniprint.IniReadValue(section, "Breed");
                if (rbr.Length > 1)
                {
                    string[] rbrs = rbr.Split(',');
                    pzX.Text = rbrs[0];
                    pzY.Text = rbrs[1];
                    pzdx.Text = rbrs[2];
                    pzzt.SelectedValue = rbrs[3];
                    pzjc.SelectedIndex = stringToInt(rbrs[4]);
                    pzxs.IsChecked = true;
                }
                else pzxs.IsChecked = false;
                string rfullName = iniprint.IniReadValue(section, "fullName");
                if (rfullName.Length > 1)
                {
                    string[] rfullNames = rfullName.Split(',');
                    fullX.Text = rfullNames[0];
                    fullY.Text = rfullNames[1];
                    fulldx.Text = rfullNames[2];
                    fullzt.SelectedValue = rfullNames[3];
                    fulljc.SelectedIndex = stringToInt(rfullNames[4]);
                    ckfull.IsChecked = true;
                }
                else ckfull.IsChecked = false;

                string rph = iniprint.IniReadValue(section, "LotNumber");
                if (rph.Length > 1)
                {
                    string[] rphs = rph.Split(',');
                    phX.Text = rphs[0];
                    phY.Text = rphs[1];
                    phdx.Text = rphs[2];
                    phzt.SelectedValue = rphs[3];
                    phjc.SelectedIndex = stringToInt(rphs[4]); 
                    phxs.IsChecked = true;
                }
                else phxs.IsChecked = false;
                string rdw = iniprint.IniReadValue(section, "ml");
                if (rdw.Length > 1)
                {
                    string[] rdws = rdw.Split(',');
                   dwX.Text = rdws[0];
                    dwY.Text = rdws[1];
                    dwdx.Text = rdws[2];
                    dwzt.SelectedValue = rdws[3];
                    dwjc.SelectedIndex= stringToInt(rdws[4]);
                    dwxs.IsChecked = true;
                }
                else dwxs.IsChecked = false;
                string rsn = iniprint.IniReadValue(section, "sn");
                if (rsn.Length > 1)
                {
                    string[] rsns = rsn.Split(',');
                    snX.Text = rsns[0];
                    snY.Text = rsns[1];
                    sndx.Text = rsns[2];
                    snzt.SelectedValue = rsns[3];
                    snjc.SelectedIndex = stringToInt(rsns[4]);
                    sn.IsChecked = true;
                }
                else sn.IsChecked = false;
                //string rshort = iniprint.IniReadValue(section, "short");
                //if (rshort.Length > 1)
                //{
                //    string[] rshorts = rshort.Split(',');
                //    jcX.Text = rshorts[0];
                //    jcY.Text = rshorts[1];
                //    jcdx.Text = rshorts[2];
                //    jczt.SelectedValue = rshorts[3];
                //    jc.IsChecked = true;
                //}
                //else jc.IsChecked = false;
                string rrq = iniprint.IniReadValue(section, "ProdDate");
                if (rrq.Length > 1)
                {
                    string[] rrqs = rrq.Split(',');
                    rqX.Text = rrqs[0];
                    rqY.Text = rrqs[1];
                    rqdx.Text = rrqs[2];
                    rqzt.SelectedValue = rrqs[3];
                    rqjc.SelectedIndex = stringToInt(rrqs[4]);
                    rqxs.IsChecked = true;
                    rqgs.Text = rrqs[5];
                }
                else rqxs.IsChecked = false;
                string rsyrq = iniprint.IniReadValue(section, "UseBefore");
                if (rsyrq.Length > 1)
                {
                    string[] rsyrqs = rsyrq.Split(',');
                    syrqX.Text = rsyrqs[0];
                    syrqY.Text = rsyrqs[1];
                    syrqdx.Text = rsyrqs[2];
                    syrqzt.SelectedValue = rsyrqs[3];
                    syrqjc.SelectedIndex = stringToInt(rsyrqs[4]);
                    syrqxs.IsChecked = true;
                    syrqgs.Text = rsyrqs[5];
                }
                else syrqxs.IsChecked = false;


                string rzdy1 = iniprint.IniReadValue(section, "ID");
                string rzdy1_ = iniprint.IniReadValue(section, "ID_");
                if (rzdy1.Length > 1)
                {
                    string[] rzdy1s = rzdy1.Split(',');
                    zdy1X.Text = rzdy1s[0];
                    zdy1Y.Text = rzdy1s[1];
                    zdy1dx.Text = rzdy1s[2];
                    zdy1zt.SelectedValue = rzdy1s[3];
                    zdy1jc.SelectedIndex = stringToInt(rzdy1s[4]);
                    zdy1xs.IsChecked = true;
                    if (zdy1xs.IsChecked == true)
                    {
                        ini.IniWriteValue("公司信息", "SelectPrintMulti", "false");//选择标签
                    }

                     string[] rzdy1s_ = rzdy1_.Split(',');
                    ebbtX.Text = rzdy1s_[0];
                    ebbtY.Text = rzdy1s_[1];
                    ebbtdx.Text = rzdy1s_[2];
                    ebbtzt.SelectedValue = rzdy1s_[3];
                    ebbtjc.SelectedIndex = stringToInt(rzdy1s_[4]);
                }
                else zdy1xs.IsChecked = false;
                string rzdy2 = iniprint.IniReadValue(section, "IDs");
                string rzdy2_ = iniprint.IniReadValue(section, "IDs_");
                if (rzdy2.Length > 1)
                {
                    string[] rzdy2s = rzdy2.Split(',');
                    zdy2X.Text = rzdy2s[0];
                    zdy2Y.Text = rzdy2s[1];
                    zdy2dx.Text = rzdy2s[2];
                    zdy2zt.SelectedValue = rzdy2s[3];
                    zdy2jc.SelectedIndex = stringToInt(rzdy2s[4]);
                    zdy2xs.IsChecked = true;
                    zdy2.Text = rzdy2s[5];
                    if (zdy2xs.IsChecked == true)
                    {
                        ini.IniWriteValue("公司信息", "SelectPrintMulti", "true");//选择标签
                    }
                    string[] rzdy2s_ = rzdy2_.Split(',');
                   ebbtX.Text = rzdy2s_[0];
                    ebbtY.Text = rzdy2s_[1];
                    ebbtdx.Text = rzdy2s_[2];
                    ebbtzt.SelectedValue = rzdy2s_[3];
                    ebbtjc.SelectedIndex = stringToInt(rzdy2s_[4]);
                    //zdy2.Text = rzdy2s_[5];
                }
                else zdy2xs.IsChecked = false;

                string den = iniprint.IniReadValue(section, "density");
                if (den.Length > 1)
                {
                    string[] densitys = den.Split(',');
                    densityX.Text = densitys[0];
                    densityY.Text = densitys[1];
                    densitydx.Text = densitys[2];
                    densityzt.SelectedValue = densitys[3];
                    densityjc.SelectedIndex = stringToInt(densitys[4]);
                    density.IsChecked = true; 
                }
                else density.IsChecked = false;

                string vit = iniprint.IniReadValue(section, "vitality");
                if (vit.Length > 1)
                {
                    string[] vits = vit.Split(',');
                    vitalityX.Text = vits[0];
                    vitalityY.Text = vits[1];
                    vitalitydx.Text = vits[2];
                    vitalityzt.SelectedValue = vits[3];
                    vitalityjc.SelectedIndex = stringToInt(vits[4]);
                    vitality.IsChecked = true; 
                }
                else vitality.IsChecked = false;

                string vaild = iniprint.IniReadValue(section, "vaild");
                if (vaild.Length > 1)
                {
                    string[] vailds = vaild.Split(',');
                    vaildX.Text = vailds[0];
                    vaildY.Text = vailds[1];
                    vailddx.Text = vailds[2];
                    vaildzt.SelectedValue = vailds[3];
                    vaildjc.SelectedIndex = stringToInt(vailds[4]);
                    ckvaild.IsChecked = true;
                }
                else ckvaild.IsChecked = false;

                string tot = iniprint.IniReadValue(section, "total");
                if (tot.Length > 1)
                {
                    string[] totals = tot.Split(',');
                   totalX.Text = totals[0];
                   totalY.Text = totals[1];
                   totaldx.Text = totals[2];
                   totalzt.SelectedValue = totals[3];
                    totaljc.SelectedIndex = stringToInt(totals[4]);
                    total.IsChecked = true;
                }
                else total.IsChecked = false;

                string lev = iniprint.IniReadValue(section, "level");
                if (lev.Length > 1)
                {
                    string[] levs = lev.Split(',');
                    levelX.Text = levs[0];
                    levelY.Text = levs[1];
                    leveldx.Text = levs[2];
                    levelzt.SelectedValue = levs[3];
                    leveljc.SelectedIndex = stringToInt(levs[4]);
                    level.IsChecked = true;
                }
                else level.IsChecked = false;

            }
            catch (Exception ex) {
                MessageBox.Show("ReadError:" + ex.Message);

            }
        }


        private void list_select(object sender, SelectionChangedEventArgs e)
        {
            try {
                string s = ((ListBoxItem)list.SelectedItem).Name;
                    //((ListBoxItem)list.SelectedItem).Name;
                if (s == "")
                {
                    tipslan.SetResourceReference(TextBlock.TextProperty, "sInfousetip");
                    MessageBox.Show(tipslan.Text);
                    return;
                }
                else {
                    InitBQ(s);
                    ini.IniWriteValue("公司信息", "SelectPrintTag", s);//选择标签
                }
            } catch(Exception ex)
            {

            }
        }

        /// <summary>
        /// 限制只能输入数字
        /// </summary>
        /// <param name="e"></param>
        public void rlimitnumber(object sender, TextCompositionEventArgs e)
        {
            //Regex.IsMatch(e.Text, @"^(/d*)([.]{0,1})(/d{0,5})$");
            Regex re = new Regex("[^0-9]+");
            //Regex re = new Regex("^(/d*)([.]{0,1})(/d{0,1})$");

            e.Handled = re.IsMatch(e.Text);

        }

        private int stringToInt(string s)
        {
            int i=0;
            try {
                i = int.Parse(s);
            } catch { }
            return i;
        }

        void Write_Docment(string msg, string docment)
        {
            UIAction(() =>
            {
                Logger.Instance.WriteLog_(msg, LogType.Information, docment);

            });
        }

        protected class ListBoxItem
        {
            public ListBoxItem(int ID, string Name)
            {
                 this.ID = ID;
                this.Name = Name;
                //this.IsActived = IsActived;
            }
            public string Name { get; set; }
            public int ID { get; set; }
        }
        protected class ComboxItem
        {
            public ComboxItem(string ID, string Name)
            {
                this.ID = ID;
                this.Name = Name;
                //this.IsActived = IsActived;
            }
            public string Name { get; set; }
            public string ID { get; set; }
        }
    }
   

}
